import React, { useEffect, useState } from "react";
import "./Personal.css";
import { Button, message, Input } from "antd";
import { getStatus, getAccountInfo, toLogout, toLogin } from "../../../utils/account";
import {
  giveRequest,
  modifypassword,
} from "../../../lib/apiconfig";

/**
 * @description 个人信息组件
 */
const Personal = () => {
  const [accountInfo, setAccountInfo] = useState({ account: "", password: "", id: "" });
  const [modifyStatus, setModifyStatus] = useState(false);
  const [newPassword, setNewPassword] = useState("");


  useEffect(() => {
    if ( getStatus() === false ) {
      message.warn("请登录!");
      setTimeout(() => {
        window.location.href="/#/login";
      }, 2000);
    } else {
      setAccountInfo(getAccountInfo());
    }
  }, []);

  // 修改密码
  const sendModify = () => {
    if ( newPassword ) {
      giveRequest(
        modifypassword,
        "POST",
        {
          status: "modifypassword",
          data: {
            id: accountInfo.id,
            account: accountInfo.account,
            password: newPassword,
          }
        },
        res => {
          const status = res.status;
          if ( status === "fail" ) {
            message.error("修改失败!");
          } else {
            message.success("修改成功");
            toLogin(res.data.account, res.data.password, res.data.id);
            setAccountInfo(getAccountInfo());
            setModifyStatus(false);
          }
        }
      );
    } else {
      message.warn("请输入新密码!");
    }
  };

  return (
    <div className="Personal-page flex-column-start-start">
      <div className="Personal-title">
        管理员{accountInfo.id}号
      </div>
      <div className="Personal-account flex-row-start-center">
        账号:   
        <div style={{ marginLeft: "10px" }}>
          {accountInfo.account}
        </div>
      </div>
      <div className="Personal-password flex-row-start-center">
        密码:  
        { modifyStatus ? (
          <div style={{ marginLeft: "10px" }}>
            <Input defaultValue={accountInfo.password} onChange={e => {
              setNewPassword(e.target.value);
            }} />
          </div>
        ) : (
          <div style={{ marginLeft: "10px" }}>
            {accountInfo.password}
          </div>
        )}
        <div style={{ marginLeft: "10px" }}>
          <Button type="link" onClick={() => {
            if ( modifyStatus === false )
              setModifyStatus(true);
            else
              sendModify();
          }}>
            { modifyStatus ? "提交修改" : "修改密码"}
          </Button>
        </div>
      </div>
      <div className="Personal-logout">
        <Button type="primary" onClick={() => {
          toLogout();
          message.success("退出登录成功");
          setTimeout(() => {
            window.location.href="/#/login";
          }, 2000);
        }}>
          退出登录
        </Button>
      </div>
    </div>
  );
}

export default Personal;